package com.zx.domain;

import com.zx.wx.wxInterface.Request;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 请求工具类
 * <功能详细描述>
 * 
 * @author  朱笑
 * @version  [版本号, 2016年7月28日 上午11:28:38]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
@Controller
public class requestUtils implements Request{
    protected static Logger logger= LogManager.getLogger(requestUtils.class);
  
	
	/** 
	 * <一句话功能简述>
	 * <功能详细描述>
	 * @param url
	 * @param json
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	public String doPost(String url, String json)  {
	    String responseMsg=null;
	    CloseableHttpClient httpclient = HttpClients.createDefault();
	    //　HttpClient中的post请求包装类 
	    HttpPost httpPost = new HttpPost(url);
	    
	    //写入字符串实体
	    StringEntity stringEntity = new StringEntity(json, "UTF-8");  
        stringEntity.setContentType("application/x-www-form-urlencoded");  
	    httpPost.setEntity(stringEntity);
	    
	    // 执行请求用execute方法
	    CloseableHttpResponse response = null;
	    try {
	        response=httpclient.execute(httpPost);
	        //获取响应状态
//	        String responseStatus=response.getStatusLine();
	        // 得到相应实体、包括响应头以及相应内容  
	        HttpEntity entity = response.getEntity();
	        // 得到response头 
//	        String responseHeader=entity.toString();
	        //获取响应内容，String类型
	        responseMsg=EntityUtils.toString(entity,"UTF-8");
	        //　关闭输入流  
	        EntityUtils.consume(entity);
	    }catch(Exception e){
	        logger.error("doPetException:"+e.getMessage());
	    } 
	    finally {
	        try
            {
                response.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
	    }
		return responseMsg;
	}
    /**
     * get方式
     * 
     * @return
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public String doGet(String url) {
        String responseMsg = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try
        {
            response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            // 得到response头 
//            String responseHeader=entity.toString();
            responseMsg=EntityUtils.toString(entity, "UTF-8");
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity);
        }
        catch (Exception e)
        {
            logger.error("doGetException:"+e.getMessage());
        }
        finally {
            try
            {
                response.close();
            }
            catch (IOException e)
            {
                logger.error("doGetIOException:"+e.getMessage());
            }
        }
        return responseMsg;
    }
    
    /** 
     * 上传文件
     * <功能详细描述>
     * @param url
     * @return
     * @throws IOException 
     * @throws ParseException 
     * @see [类、类#方法、类#成员]
     */
    public String filePost(String url ,String filePath) {
         String responseMsg="";
         CloseableHttpClient httpclient = HttpClients.createDefault();
         HttpPost httppost=new HttpPost(url);
         File file=new File(filePath);
         if (file != null) {
             HttpEntity entity = MultipartEntityBuilder
                   .create()
                   .addBinaryBody("media", file)
                   .setMode(HttpMultipartMode.RFC6532)
                   .build();
             httppost.setEntity(entity);
             httppost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
           }
         CloseableHttpResponse response;
        try
        {
            response = httpclient.execute(httppost);
            HttpEntity entity2 = response.getEntity();
            responseMsg=EntityUtils.toString(entity2,"UTF-8");
        }
        catch (Exception e)
        {
            logger.error("filepost:"+e.getMessage());
        }
        return responseMsg;
    }
    
    
    /**
     * 上传微信视频专用
     * 
     * @param url
     * @param filePath
     * @param title
     * @param introduction
     * @return
     */
    public static String postFile(String url, String filePath, String title, String introduction)
    {
        File file = new File(filePath);
        if (!file.exists())
            return null;
        String result = null;
        try
        {
            URL url1 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)url1.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept",
                "textml,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
            conn.setRequestProperty("Cache-Control", "max-age=0");
            String boundary = "-----------------------------" + System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            
            OutputStream output = conn.getOutputStream();
            output.write(("--" + boundary + "\r\n").getBytes());
            // output.write(String.format("Content-Disposition: form-data; name=\"media\";
            // filename=\"%s\"\r\n",file.getName()).getBytes());
            output.write(
                String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"; filelength=\"%s\"\r\n",
                    file.getName(),
                    file.length()).getBytes());
            output.write("Content-Type: image/png \r\n\r\n".getBytes());
            byte[] data = new byte[1024];
            int len = 0;
            FileInputStream input = new FileInputStream(file);
            while ((len = input.read(data)) > -1)
            {
                output.write(data, 0, len);
            }
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
            output.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}", title, introduction).getBytes());
            output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
            output.flush();
            output.close();
            input.close();
            InputStream resp = conn.getInputStream();
            StringBuffer sb = new StringBuffer();
            while ((len = resp.read(data)) > -1)
                sb.append(new String(data, 0, len, "utf-8"));
            resp.close();
            result = sb.toString();
            System.out.println(result);
        }
        catch (ClientProtocolException e)
        {
            logger.error("postFile，不支持http协议", e);
        }
        catch (IOException e)
        {
            logger.error("postFile数据传输失败", e);
        }
        logger.info("result=" + result);
        return result;
    }

    //代码未写，需要则沟通
//  public static String doPost(String url, )  {
//        String responseMsg=null;
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//        //　HttpClient中的post请求包装类 
//        HttpPost httpPost = new HttpPost(url);
//        
//     // nvps是包装请求参数的list 
////      List <NameValuePair> nvps = new ArrayList <NameValuePair>(); //写入实体
////      nvps.add(new BasicNameValuePair("username", "vip"));
////      nvps.add(new BasicNameValuePair("password", "secret"));
////        httpPost.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
//        // 执行请求用execute方法
//        CloseableHttpResponse response = null;
//        try {
//            response=httpclient.execute(httpPost);
//            //获取响应状态
////          String responseStatus=response.getStatusLine();
//            // 得到相应实体、包括响应头以及相应内容  
//            HttpEntity entity = response.getEntity();
//            // 得到response头 
////          String responseHeader=entity.toString();
//            //获取响应内容，String类型
//            responseMsg=EntityUtils.toString(entity);
//            //　关闭输入流  
//            EntityUtils.consume(entity);
//        }catch(Exception e){
//            
//        } 
//        finally {
//            try
//            {
//                response.close();
//            }
//            catch (IOException e)
//            {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
//        return responseMsg;
//    }
}
